﻿using System;
using System.Collections;
using System.Data;
using System.Text;

namespace MJHDataService
{
    public class DataSetUtility
    {
        public static DataSet TransformFlatToHierarchy(DataTable dtSrc,int nHighestLevel,string sPrimaryKey,string sParentKey)
        {
            DataSet ds = new DataSet();

            for (int i = 0; i <= nHighestLevel; i++)
            {
                DataRow[] aDr = dtSrc.Select(string.Format("Level = {0}", i));
                if (aDr.Length > 0)
                {
                    using (DataTable dtLevel = dtSrc.Clone())
                    {
                        dtLevel.TableName = string.Format("Level{0}", i);
                        foreach (DataRow dr in aDr)
                        {
                            DataRow nr = dtLevel.NewRow();
                            foreach (DataColumn dc in dtSrc.Columns)
                            {
                                nr[dc.ColumnName] = dr[dc.ColumnName];
                            }
                            dtLevel.Rows.Add(nr);
                        }
                        dtLevel.PrimaryKey = new DataColumn[] { dtLevel.Columns[sPrimaryKey] };
                        ds.Tables.Add(dtLevel);
                    }
                    if (i > 0)
                    {
                        int nParentLevel = i - 1;
                        string sCurrLevel = string.Format("Level{0}", i);
                        string sParentLevel = string.Format("Level{0}", nParentLevel);

                        DataRelation dRel = new DataRelation(sCurrLevel, ds.Tables[sParentLevel].Columns[sPrimaryKey], ds.Tables[sCurrLevel].Columns[sParentKey]);

                        ds.Relations.Add(dRel);
                    }
                }
            }

            return ds;
        }
    }
}
